<template>
  <div id="page-play" class="page-play">
    <div v-for="item in 10" :key="item">
      <h1>img</h1>
      longlonglable
    </div>
    <div>
      <h1>img</h1>
      <img id="img-monkey" :src="srcChoose" alt="img" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";

const srcList = ref([
  {
    src: "/歇逼猴.png",
    name: "歇逼猴",
  },
]);

// 响应式状态来跟踪图片是否在视口中
const isImageInViewport = ref(false); //应该使用响应式而不是传参

const checkImageInViewport = () => {
  let imgElement = document.getElementById("img-monkey");
  if (!imgElement) return false;

  const rect = imgElement.getBoundingClientRect();
  const isInViewport =
    // rect.top >= 0 && 窗口会抽搐，边缘滚动会导致图片反复加载
    // rect.left >= 0 &&
    // rect.bottom <=
    //   (window.innerHeight || document.documentElement.clientHeight) &&
    // rect.right <= (window.innerWidth || document.documentElement.clientWidth);
    rect.top < window.innerHeight && //top是图片的顶部距离元素顶部的距离，如果top小于窗口高度，则图片在视口中
    rect.bottom > 0 &&
    rect.left < window.innerWidth &&
    rect.right > 0;
  //width是图片的宽度，height是图片的高度，所以无法用width和height来判断图片是否在视口中

  console.log("图片是否在视口中:", isInViewport);
  console.log(rect);
  console.log(window.innerHeight);
  console.log(window.innerWidth);
  isImageInViewport.value = isInViewport;
  return isInViewport;
};

const srcChoose = computed(() => {
  if (isImageInViewport.value) {
    return srcList.value[0].src;
  }
  return ""; // 或者返回一个占位符图片
});

onMounted(() => {
  // 初始检查
  checkImageInViewport();
  // 添加滚动事件监听器
  window.addEventListener("scroll", checkImageInViewport);
});

onUnmounted(() => {
  window.removeEventListener("scroll", checkImageInViewport);
});
</script>

<style scoped>
.page-play {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  overflow: auto;
}
</style>
